<?php
include('../connect.php');

session_start();
$uid=$_SESSION['uid'];
$sname = $_SESSION['firstname'].' '.$_SESSION['lastname'];
$pic=$_SESSION['pic_path'];

//////////////////////////////////////////////////////////

	function checkValues($value)
	{
		 $value = trim($value);
		 
		if (get_magic_quotes_gpc()) {
			$value = stripslashes($value);
		}
		
		 $value = strtr($value,array_flip(get_html_translation_table(HTML_ENTITIES)));
		
		 $value = strip_tags($value);
		 $value = mysql_real_escape_string($value);
		 $value = htmlspecialchars ($value);
		 return $value;
		
	}
	function clickable_link($text = '')
	{
		$text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text);
		$ret = ' ' . $text;
		$ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $ret);
		
		$ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $ret);
		$ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret);
		$ret = substr($ret, 1);
		return $ret;
	}
	
	$next_records = 10;
	$show_more_button = 0;
	
	if(checkValues($_GET['value']))
	{
		$userip = $_SERVER['REMOTE_ADDR'];
		
		echo "INSERT INTO g_posts (post,uid_fk,name,ip,created,xcreated) 
				VALUES('".checkValues($_GET['value'])."','".$_SESSION['uid']."','".$sname."','".$userip."','".date("Y-m-d H:i:s")."','".strtotime(date("Y-m-d H:i:s"))."')";
		
		mysql_query("INSERT INTO g_posts (post,uid_fk,name,ip,created,xcreated) 
				VALUES('".checkValues($_GET['value'])."','".$_SESSION['uid']."','".$sname."','".$userip."','".date("Y-m-d H:i:s")."','".strtotime(date("Y-m-d H:i:s"))."')");
	
		$result = mysql_query("SELECT *,
		UNIX_TIMESTAMP() - xcreated AS TimeSpent FROM g_posts order by post_id desc limit 1");
	
	}
		elseif($_GET['show_more_post']) // more posting paging
	{
		$next_records = $_GET['show_more_post'] + 10;
		
		$result = mysql_query("SELECT *,
		UNIX_TIMESTAMP() - xcreated AS TimeSpent FROM g_posts order by post_id desc limit ".$_GET['show_more_post'].", 10");
		
		$check_res = mysql_query("SELECT * FROM g_posts order by post_id desc limit ".$next_records.", 10");
		
		$show_more_button = 0; // button in the end
		
		$check_result = mysql_num_rows(@$check_res);
		if($check_result > 0)
		{
			$show_more_button = 1;
		}
	}
	//////////////////////////////
	//elseif($_GET['image_file']&&isset($_POST)){
		
		elseif($_GET['action']){
		$image_name = $_FILES['image_file']['name'];
$image_tmp_name = $_FILES['image_file']['tmp_name'];
$image_type = strtolower(substr($image_name,strpos($image_name,'.')+1));
if(isset($image_name)){
	if(!empty($image_name)){
        if($image_type=='jpg'||$image_type=='png'||$image_type=='gif'){
            if(list($width,$height) = getimagesize($image_tmp_name)){
				$array = array(300,640);
				foreach($array as &$max_size){
					if($width<=$max_size && $height<=$max_size){
						$new_width = $width;
						$new_height = $height;
						$res_img = imagecreatetruecolor($new_width,$new_height);
						if($image_type == "jpg"){
							$source_img = imagecreatefromjpeg($image_tmp_name);
						}elseif($image_type == "png"){
							$source_img = imagecreatefrompng($image_tmp_name);
						}elseif($image_type == "gif"){
							$source_img = imagecreatefromgif($image_tmp_name);
						}else{
							//$upload_error = '<div class="up_error">Sorry, an error occurred. Please try again.</div>';
							echo "{";
							echo	"error: 'Sorry, an error ocurred'";
							echo "}";
							exit(0);
							}
						imagecopyresized($res_img, $source_img,0,0,0,0,$new_width,$new_height,$width,$height);
						$date_time = str_replace('-'&' '&':','',date("Y-m-d H:i:s")); 
						$image_name = $_SESSION['uid'].'_'.$date_time.'.png';
						$userip = $_SERVER['REMOTE_ADDR'];
						
						if($max_size == 300){
						imagepng($res_img,'uploads/300size/'.$image_name);
						//imagepng($res_img,'uploads/640size/'.$image_name);
						mysql_query("INSERT INTO g_posts (post,uid_fk,name,ip,created,xcreated) 
						VALUES('".$image_name."','".$_SESSION['uid']."','".$sname."','".$userip."','".date("Y-m-d H:i:s")."','".strtotime(date("Y-m-d H:i:s"))."') ");
						}else{
						imagepng($res_img,'uploads/640size/'.$image_name);
							
							}
						
						}else{
							if($width>=$height){
								$old_max = $width;
								}else{ $old_max = $height; }
								$ratio = $max_size/$old_max;
								$new_width = $ratio * $width;
								$new_height = $ratio * $height;
								
								$res_img = imagecreatetruecolor($new_width,$new_height);
								if($image_type == "jpg"){
									$source_img = imagecreatefromjpeg($image_tmp_name);
								}elseif($image_type == "png"){
									$source_img = imagecreatefrompng($image_tmp_name);
								}elseif($image_type == "gif"){
									$source_img = imagecreatefromgif($image_tmp_name);
								}else{
									//$upload_error = '<div class="up_error">Sorry, an error occurred. Please try again.</div>';
									echo "{";
									echo	"error: 'Sorry, an error ocurred'";
									echo "}";
									exit(0);
									}
								imagecopyresized($res_img, $source_img,0,0,0,0,$new_width,$new_height,$width,$height);
								$date_time = str_replace('-'&' '&':','',date("Y-m-d H:i:s")); 
								$image_name = $_SESSION['uid'].'_'.$date_time.'.png';
								
								if($max_size==300){
									$userip = $_SERVER['REMOTE_ADDR'];
									mysql_query("INSERT INTO g_posts (post,uid_fk,name,ip,created,xcreated) 
									VALUES('".$image_name."','".$_SESSION['uid']."','".$sname."','".$userip."','".date("Y-m-d H:i:s")."','".strtotime(date("Y-m-d H:i:s"))."') ");
									imagepng($res_img,'uploads/300size/'.$image_name);
									}else{
										imagepng($res_img,'uploads/640size/'.$image_name);
										}
										
										imagedestroy($res_img);
										imagedestroy($source_img);
							}
					}
					  
					  echo "{";
					  echo		"msg: '".$image_name."'\n";
					  echo "}"; 
					  break;
					
					
                }else{
                //$upload_error = '<div class="up_error">Sorry, chosen file wasn\'t an Image file</div>';
				echo "{";
				echo "error: 'Sorry, file is not an Image file'";
				echo "}";
				exit(0);
                }
          }else{
             //$upload_error = '<div class="up_error">Sorry, chosen image was not of jpg/png/gif format.</div>';
			 echo "{";
			 echo "error: 'Sorry, chosen image not of jpg/png/gif format.'";
			 echo "}";
			 exit(0);
          }
	}else{
    //$upload_error = '<div class="up_error">Sorry, no file was chosen.</div>';
	echo "{";
	echo "error: 'Please, choose a an image file'";
	echo "}";
	exit(0);
    }
}
		
		}
	else
	{	
		$show_more_button = 1;
		$result = mysql_query("SELECT *,
		UNIX_TIMESTAMP() - xcreated AS TimeSpent FROM g_posts order by post_id desc limit 0,10");
		}
	
	?>
	         
    <div><?php echo $upload_error; ?></div>
    
    
	<div id="upload">
    	<img src="../images/loading2.gif" style="float:right; display:none;"  />
    	<form action="" enctype="multipart/form-data" method="post" id="pic_upload_form" class="pic_upload_form" style="display:none;">
            <label style="font-size:12px; color:#000;"> Upload a picture from your Computer.</label><br />
            <input type="file" name="image_file" id="image_file" class="image_file" />
            <input type="submit" name="upload" class="upload" id="upload" value="upload" onClick="return ajaxFileUpload();"/>
            <div class="button_inside_border" id="upload_button">Upload</div>
    	</form>
    </div>
	<?php
	while ($row = mysql_fetch_array($result))
	{
		$comments = mysql_query("SELECT *,
		UNIX_TIMESTAMP() - xcreated AS CommentTimeSpent FROM comments where post_id_fk = ".$row['post_id']." order by com_id asc"); 
		$pic_path = 'prof_pics/50size/'.$row['uid_fk'].'_propic.png';
		$name = $row['name'];
		$status_msg = clickable_link($row['post']);
		
		$weeks = floor($row['Timespent']/(60*60*24*7));
		$days = floor($row['TimeSpent']/(60*60*24));
		$remainder = $row['TimeSpent']%(60*60*24);
		$hours = floor($remainder/(60*60));
		$remainder = $remainder%(60*60);
		$minutes = floor($remainder/60);
		$seconds = $remainder%60;
		
		if($days == 0 && $hours == 0 && $minutes == 0){
			$when = 'A few seconds ago ';
		}elseif($days == 0 && $hours == 0){
			if($minutes==1){
			$when = 'A minute ago ';	
			}else{
			$when = $minutes.'minutes ago '; }
		}elseif($days == 0){
			if($hours == 1){
			$when = 'An hour ago ';
			}else{
			$when = $hours.' hours ago '; }
		}elseif($days > 0 && $days < 7){
			if($days==1){
				$when = 'Yesterday';
				}else{
				$when = $days.' days ago.';	
				}
		}elseif($weeks > 0 && $weeks < 4 ){
			if($weeks == 1){
				$when = 'Last week';
				}else{
					$when = $weeks.' weeks ago';
					}
		}else{
			$when = date('F d Y',$row['xcreated']);
			}
		
		$pname_query = mysql_query("SELECT * FROM bannau WHERE uid = ".$row['uid_fk']."");
		$pname_row = mysql_fetch_array($pname_query);
		$pname = $pname_row['firstname'].' '.$pname_row['lastname'];
	
?>
       
	<div class="load_status" id="record-<?php echo $row['post_id']; ?>" style="width:520px; height:auto;">
		
		<div class="post_cont" style="width:520px; min-height:50px">
        	<div class="post_img" align="right" style="float:left; min-height:52px; width:52px; margin-left:10px;">
			<a href="../myhome.php?my_uid=<?php echo $row['uid_fk']; ?>" class=""><img src= "<?php echo '../prof_pics/50size'.$row['uid_fk'].'_propic.png'; ?>" /></a>
			</div>
            <div class="post_cont" id="post_cont_bx" style="width:450px; min-height:60px; float:right;">
                <div class="status_text">
                    <a href="../myhome.php?my_uid=<?php echo $row['uid_fk']; ?>" class="page_info_names">
                    <?php echo $pname; ?></a><br>
                    <?php 
					$msg_type = strtolower(substr($row['post'],strpos($row['post'],'.')));
					if($msg_type == '.png'){
						 echo '<a class="group1" href="uploads/640size/'.$row['post'].'"><img src= "uploads/300size/'.$row['post'].'"/></a><br>';
						}else{
					echo '<label>'.$row['post'].'</label><br>'; 
					}
					?>
                    <label class="post_cmt_detail"><?php echo $when; ?> | <a href="javascript: void(0)" id="post_id<?php echo $row['post_id']; ?>" class="showCommentBox">Comment</a> | </label>
                    <?php if($_SESSION['uid']==$row['uid_fk']){?>
                    <a href="" class="deletee" style=" display:none;">Remove</a>
                    <? }?>
                </div>
                
            </div>
        
        </div>
        
        <br clear="all" />
        
        <div class="commentPosted" id="CommentPosted<?php echo $row['post_id'];?>" style="margin-left:70px; width:450px;">
			<?php 
            $comment_row_num = mysql_num_rows(@$comments);
			if($comment_row_num > 0){
				
				while($rows = mysql_fetch_array($comments)){
					$weeksc = floor($rows['CommentTimeSpent']/(60*60*24*7));
					$daysc = floor($rows['CommentTimeSpent']/(60*60*24));
					$remainderc = $rows['CommentTimeSpent']%(60*60*24);
					$hoursc = floor($remainderc/(60*60));
					$remainderc = floor($remainderc%(60*60));
					$minutesc = floor($remainderc/60);
					$secondsc = $remainder%60;
					if($weeksc > 3){
						$cwhen = date('F d Y', $rows['xcreated']);
					}elseif($weeksc > 0){
						if($weeksc == 1){
							$cwhen = 'Last week';
							}else{
								$cwhen = $weeksc.' weeks ago';
								}
					}elseif($daysc > 0){
						if($daysc==1){
							$cwhen = 'Yesterday';
							}else{
								$cwhen = $daysc.' days ago';
								}
					}elseif($daysc == 0 && $hoursc == 0 && $minutesc == 0){
						$cwhen = "few seconds ago";	}elseif($daysc == 0 && $hoursc == 0){
						if($minutesc == 1){
							$cwhen ='About a minute ago'; 
						}else{ $cwhen = $minutesc.' minutes ago'; }
					}elseif($daysc == 0){
						if($hoursc == 1){
							$cwhen = 'About an hour ago';
							}else{
							$cwhen = $hoursc.' hours ago';
							}
						}
					else{}
					
            ?>
         <?php 
		 $cname_query = mysql_query("SELECT * FROM bannau WHERE uid = ".$rows['uid_fk']."");
		 $cname_row = mysql_fetch_array($cname_query);
		 $cname = $cname_row['firstname'].' '.$cname_row['lastname'];
		 ?>
         
		  		<div class="comt_contn" id="record-<?php echo $rows['com_id']; ?>">
          			<div class="comt_pic" style="float:left; width:40px; min-height:40px; margin-top:1px;">
                    	<a href="../myhome.php?my_uid=<?php echo $rows['uid_fk']; ?>" class=""><img class="comt_pic" src="<?php echo '../prof_pics/40size'.$rows['uid_fk'].'_propic.png' ?>" /></a>
                	</div>
                    <div class="comt_msg" style="float:left; min-height:40px; width:390px;">
						<div class="status_text"><a href="../myhome.php?my_uid=<?php echo $rows['uid_fk']; ?>" class="page_info_names" style="float:left;">
                    	<?php echo $cname; ?></a>&nbsp;
                        <?php echo $rows['com_msg']; ?>
                        <?php echo '<br><label class="post_cmt_detail">'.$cwhen.'</label>'; ?> &middot;
                            <?php if($uid == $rows['uid_fk']){ ?>
								<a href="#" id="CID-<?php echo $rows['com_id']; ?>" class="c_delete" style="color:#00F;">Delete</a>
							<?php }?>
                         </div>
					</div>
                    
				</div>
			<hr style="color:#FFFFFF; size:2px;"/>
         <?
        }  
        } ?>
       </div>		
            <div class="commentBox" id="commentBox-<?php echo $row['post_id'];?>" <?php echo (($comment_row_num) ? '' : 'style="display:none"')?> style="font-size:12px; width:450px; min-height:40px; margin-left:80px;" >
                <a href="../myhome.php?my_uid=<?php echo $uid; ?>"><img class="iframe comt_pic" src="<?php echo '../prof_pics/40size'.$uid.'_propic.png' ?>" style="float:left; width:30px; height:30px;"/></a>						
                <a href="../myhome.php?my_uid=<?php echo $uid; ?>" id="u_name" class="page_info_names" style ="margin-left:5px;">
				<?php echo $sname; ?></a><br>
                <label class="text_comt" id="record-<?php echo $row['post_id']; ?>">
                <textarea name="comment_msg_bx" class="comment_msg_bx" id="comment_msg_bx-<?php echo $row['post_id']; ?>" style="width:360px; margin-left:5px; border: solid #CF0 1px; min-height:15px;"></textarea>
                
                </label><br />
                <a id="SubmitComment" class="small button comment" style="float:left; font-size:11px; border:#F00 solid 1px; 
                background-color:#D0FC4C; padding:2px 2px 2px; margin-left:40px;">Post Comment</a>
                <br clear="all" />
            </div>
		</div>

        

<?php
}
if($show_more_button == 1){?>
    <div id="bottomMoreButton" align="center" style="text-align:center; font-size:12px; color:#000000;">
    	<a id="more_<?php echo @$next_records ?>" class="more_records" href="javascript: void(0)" style="border:#F00 solid 1px; padding:2px 2px 2px 2px; background-color:#D0FC4C; color:#000000;">Load older Posts</a>
    </div>
<?php } ?>
